// pages/profile/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {}
  },

  onShow() {
    let userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo
    })
  },

  /** 用户选择头像 */
  chooseAvatar(ev) {
    // console.log(ev);
    let avatar = ev.detail.avatarUrl
    let token = getApp().token
    wx.uploadFile({
      url: wx.http.baseURL + '/upload',
      filePath: avatar,
      name: 'file',
      header: {
        Authorization: `Bearer ${token}`
      },
      formData: {
        type: 'avatar'
      },
      success: async (res) => {
        // console.log(res);
        let data = JSON.parse(res.data)
        let avatarUrl = data.data.url
        // console.log(avatarUrl);

        let putRes = await wx.http({
          url: '/userInfo',
          method: 'put',
          data: {
            avatar: avatarUrl
          }
        })

        // console.log(putRes);
        if (putRes.code === 10000) {
          wx.utils.toast('修改头像成功！')
          // this.setData({
          //   "userInfo.avatar": avatarUrl
          // })
        }
      }
    })
  },

  /** 用户输入昵称 */
  async nicknameIpt(ev) {
    // console.log(ev.detail);
    let nickName = ev.detail
    if (!nickName) {
      return wx.utils.toast('昵称不能为空！')
    }
    let res = await wx.http({
      url: '/userInfo',
      method: 'put',
      data: {
        nickName
      }
    })
    // console.log(res);
    if (res.code === 10000) {
      wx.utils.toast('修改用户昵称成功！')
      this.setData({
        "userInfo.nickName": nickName
      })
    }
  }
})